package com.tiyende.kash.loop.ui.fragment

import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import androidx.core.graphics.toColorInt
import com.tiyende.kash.loop.R
import com.tiyende.kash.loop.common.CommonFragment
import com.tiyende.kash.loop.configs.TiyendeApiUrl.addCommonParams
import com.tiyende.kash.loop.databinding.TiyendeActivityFeedbackQuestionTypeItemBinding
import com.tiyende.kash.loop.databinding.TiyendeFragmentAuthenticationStepUsedAppBinding
import com.tiyende.kash.loop.event.TiyendeEventData
import com.tiyende.kash.loop.event.TiyendeEventPointType
import com.tiyende.kash.loop.ui.activity.TiyendeAuthenticationStepsActivity
import com.tiyende.kash.loop.utils.track.TrackPointManager
import org.json.JSONObject

/**
 * TiyendeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/19 10:38
 * @Annotation：认证流程 - 常用APP
 */
class TiyendeAuthenticationStepUsedAppFragment(): CommonFragment() {
    private var _binding: TiyendeFragmentAuthenticationStepUsedAppBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot used apps binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )
    private var stepItem: JSONObject? = null
    private var stepTitle = ""
    private var appList: ArrayList<JSONObject>? = null
    constructor(stepItem: JSONObject): this(){
        this.stepItem = stepItem
        stepTitle = stepItem.optString("stepTitle")
    }

    override fun getTiyendeRootView(inflater: LayoutInflater): View {
        _binding = TiyendeFragmentAuthenticationStepUsedAppBinding.inflate(inflater)
        return binding.root
    }

    override fun initTiyendeView() {
        stepItem?.let {
            val showKey = "*"
            val showText = it.optString("title")
            val startIndex = showText.indexOf(showKey)
            val dataSecuritySpannable = SpannableString(showText)
            dataSecuritySpannable.setSpan(ForegroundColorSpan("#FFFF3939".toColorInt()), startIndex, startIndex + showKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            _binding?.textStepUsedAppTitle?.text = dataSecuritySpannable
        }

        //提交按钮移到外层，通过通知的方式控制提交
        _binding?.btnUsedAppSubmit?.visibility = View.INVISIBLE
    }

    override fun initTiyendeListener() {
        //提交
        _binding?.btnUsedAppSubmit?.setOnClickListener {
            onTiyendeSubmitAuthenticationInfoAction()
        }
    }

    override fun loadTiyendeData() {
        stepItem?.let {
            addEventPointRequestAction(String.format(TiyendeEventPointType.PAGE.TIYENDE_PAGE_STEP_XX_START,stepTitle))
            if (appList == null){
                appList = arrayListOf()
            }
            val values = it.optJSONArray("values")
            values?.let { array ->
                for (i in 0..< array.length()){
                    val item = JSONObject()
                    item.put("title",array.optString(i))
                    item.put("isSelect", false)
                    appList?.add(item)
                }
                showTiyendeUsedAppListView()
            }
        }
    }

    /**
     * 设置常用APP列表
     */
    private fun showTiyendeUsedAppListView(){
        binding.usedAppsFlexbox.removeAllViews()
        appList?.let { list ->
            for (i in 0..< list.size) {
                val item = list[i]
                val itemBinding = TiyendeActivityFeedbackQuestionTypeItemBinding.inflate(layoutInflater)
                itemBinding.textType.text = item.optString("title")
                if (item.optBoolean("isSelect")){
                    itemBinding.textType.setTextColor("#FFFFFFFF".toColorInt())
                    itemBinding.textType.shapeDrawableBuilder
                        .setSolidColor("#FF1F2937".toColorInt())
                        .setStrokeColor("#FF3ED9AB".toColorInt())
                        .intoBackground()
                } else {
                    itemBinding.textType.setTextColor("#FFFFFFFF".toColorInt())
                    itemBinding.textType.shapeDrawableBuilder
                        .setSolidColor("#FF1F2937".toColorInt())
                        .setStrokeColor("#FF334155".toColorInt())
                        .intoBackground()
                }
                binding.usedAppsFlexbox.addView(itemBinding.root)
                itemBinding.textType.setOnClickListener {
                    if (!item.optBoolean("isSelect") && gTiyendeSelectedCount() >= 4){
                        return@setOnClickListener
                    }
                    item.put("isSelect",!item.optBoolean("isSelect"))
                    if (item.optBoolean("isSelect")){
                        stepItem?.let {
                            val stepRemark = "${stepTitle}_${it.optString("paramName")}"
                            addEventPointRequestAction(String.format(TiyendeEventPointType.CLICK.TIYENDE_CLICK_STEP_XX_SELECT,stepRemark),gTiyendeSelectedItemTitles())
                        }
                    }
                    showTiyendeUsedAppListView()
                }
            }
        }
    }

    /**
     * 获取选中的Item数量
     */
    private fun gTiyendeSelectedCount(): Int{
        var count = 0
        appList?.let { list ->
            list.forEach {
                if (it.optBoolean("isSelect")){
                    count += 1
                }
            }
        }
        return count
    }

    /**
     * 获取选中的APP名称
     */
    private fun gTiyendeSelectedItemTitles(): String{
        var titles = ""
        appList?.let { list ->
            list.forEach {
                if (it.optBoolean("isSelect")){
                    titles += "${it.optString("title")},"
                }
            }
        }
        if (titles.isNotEmpty()){
            titles = titles.substring(0,titles.length - 1)
        }
        return titles
    }

    /**
     * 提交进件信息
     */
    private fun onTiyendeSubmitAuthenticationInfoAction(){
        _binding?.root?.clearFocus()
        addEventPointRequestAction(String.format(TiyendeEventPointType.CLICK.TIYENDE_CLICK_STEP_XX_NEXT, stepTitle),"")
        if (gTiyendeSelectedCount() < 4){
            showErrorTipsDialog(getString(R.string.tiyende_dialog_tips_submit_error), stepTitle)
            return
        }
        stepItem?.let {
            val params = JSONObject().addCommonParams().apply {
                put("path",it.optString("apiUrl").replace("/",""))
                put(it.optString("paramName"),gTiyendeSelectedItemTitles())
            }
            // TODO: Step Next 批量埋点上报
            TrackPointManager.getInstance().manualReport()

            val act = getAct() as TiyendeAuthenticationStepsActivity
            act.onAuthenticationStepSubmitAction(params)
        }
    }

    override fun onTiyendePublishEvent(event: TiyendeEventData) {
        super.onTiyendePublishEvent(event)
        when(event.eventType){
            TiyendeEventData.TYPE.TIYENDE_SUBMIT_AUTHENTICATION -> {
                onTiyendeSubmitAuthenticationInfoAction()
            }
            else -> {

            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(String.format(TiyendeEventPointType.PAGE.TIYENDE_PAGE_STEP_XX_END,stepTitle))
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}